<template>
  <div>
    <Dialog
      :show="dialogConfig.show"
      :title="dialogConfig.title"
      :buttons="dialogConfig.buttons"
      width="400px"
      :showCancel="false"
      @close="dialogConfig.show = false"
    >
      <el-form
        :model="formData"
        :rules="rules"
        ref="formDataRef"
        label-width="100px"
        @submit.prevent
      >
        <el-form-item label="邮箱" prop="email">
          <el-input
            size="large"
            v-model.trim="formData.email"
            :value="userInfo.email"
            :disabled="true"
          >
            <template #prefix>
              <span class="iconfont icon-account"></span>
            </template>
          </el-input>
        </el-form-item>
        <!-- 邮箱验证码 -->
        <el-form-item label="邮箱验证码" prop="emailCode">
          <div class="send-email-panel">
            <el-input
              clearable
              size="large"
              placeholder="请输入邮箱验证码"
              v-model="formData.emailCode"
            >
              <template #prefix>
                <span class="iconfont icon-checkcode"></span> </template
            ></el-input>
            <el-button
              class="send-mail-btn"
              type="primary"
              plain
              size="large"
              @click="getEmailCode"
              ><span>发送验证码</span></el-button
            >
          </div>
        </el-form-item>
        <!--input输入-->
        <el-form-item label="新密码" prop="password">
          <el-input
            type="password"
            size="large"
            placeholder="请输入密码"
            v-model="formData.password"
            show-password
          >
            <template #prefix>
              <span class="iconfont icon-password"></span>
            </template>
          </el-input>
        </el-form-item>

        <!--input输入-->
        <el-form-item label="确认密码" prop="rePassword">
          <el-input
            type="password"
            size="large"
            placeholder="请再次输入密码"
            v-model="formData.rePassword"
            show-password
          >
            <template #prefix>
              <span class="iconfont icon-password"></span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="checkCode" label="验证码">
          <div class="check-code-panel">
            <el-input
              size="large"
              placeholder="请输入验证码"
              v-model.trim="formData.checkCode"
              @keyup.enter="doSubmit"
            >
              <template #prefix>
                <span class="iconfont icon-checkcode"></span>
              </template>
            </el-input>
            <img
              :src="checkCodeUrl"
              class="check-code"
              @click="changeCheckCode(0)"
            />
          </div>
        </el-form-item>
      </el-form>
    </Dialog>
    <Dialog
      :show="dialogConfig4SendMailCode.show"
      :title="dialogConfig4SendMailCode.title"
      :buttons="dialogConfig4SendMailCode.buttons"
      width="400px"
      :showCancel="false"
      @close="dialogConfig4SendMailCode.show = false"
    >
      <el-form
        :model="formData4SendMailCode"
        :rules="rules"
        ref="formData4SendMailCodeRef"
        label-width="80px"
        @submit.prevent
      >
        <el-form-item label="邮箱:">
          {{ userInfo.email }}
        </el-form-item>
        <el-form-item label="验证码:" prop="checkCode">
          <div class="check-code-panel">
            <el-input
              size="large"
              placeholder="请输入验证码"
              v-model.trim="formData4SendMailCode.checkCode"
            >
              <template #prefix>
                <span class="iconfont icon-checkcode"></span>
              </template>
            </el-input>
            <img
              :src="checkCodeUrl4SendMailCode"
              class="check-code"
              @click="changeCheckCode(1)"
            />
          </div>
        </el-form-item>
      </el-form>
      <!--验证码-->
    </Dialog>
  </div>
</template>

<script setup>
import { ref, reactive, getCurrentInstance, nextTick, compile } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ResetPwd, SendEmailCode } from "@/api/account.js";
const { proxy } = getCurrentInstance();
const router = useRouter();
const route = useRoute();
const api = {
  // 验证码
  checkCode: "/api/checkCode",
};
const checkCodeUrl = ref(api.checkCode);
const checkCodeUrl4SendMailCode = ref(api.checkCode);
const userInfo = ref(proxy.VueCookies.get("userInfo"));
// 检查密码是否一致
const checkRePassword = (rule, value, callback) => {
  if (value !== formData.value.password) {
    callback(new Error(rule.message));
  } else {
    callback();
  }
};

const formData = ref({});
const formDataRef = ref();
const rules = {
  emailCode: [{ required: true, message: "请输入邮箱验证码" }],
  password: [
    { required: true, message: "请输入密码" },
    {
      validator: proxy.Verify.password,
      message: "密码只能是数字、字母、特殊字符，8-18位",
    },
  ],
  rePassword: [
    { required: true, message: "请输入确认密码" },
    { validator: checkRePassword, message: "两次密码输入不一致" },
  ],
};
const show = () => {
  dialogConfig.value.show = true;
  nextTick(() => {
    formDataRef.value.resetFields();
    formData.value = {};
  });
};
defineExpose({ show });
const dialogConfig = ref({
  show: false,
  title: "修改密码",
  buttons: [
    {
      type: "primary",
      text: "确定",
      click: (e) => {
        submitForm();
      },
    },
  ],
});

const submitForm = async () => {
  formDataRef.value.validate(async (valid) => {
    if (!valid) {
      return;
    }

    let params = {
      email: proxy.VueCookies.get("userInfo").email,
      password: formData.value.password,
      emailCode: formData.value.emailCode,
      checkCode: formData.value.checkCode,
    };
    console.log(params);
    const res = await ResetPwd(params, () => {
      changeCheckCode(0);
    });
    if (!res) {
      return;
    }
    dialogConfig.value.show = false;
    proxy.Message.success("密码修改成功");
  });
};
// 打开验证码弹窗（发送邮箱验证码）
const getEmailCode = () => {
  // 校验表单
  formDataRef.value.validateField("email", (valid) => {
    if (!valid) {
      return;
    }
    dialogConfig4SendMailCode.show = true;
    // 打开弹框要清空数据
    nextTick(() => {
      changeCheckCode(1);
      formData4SendMailCodeRef.value.resetFields();
      formData4SendMailCode.value = {
        email: formData.value.email,
      };
    });
  });
};
// 发送邮箱验证码
const formData4SendMailCode = ref({});
const formData4SendMailCodeRef = ref();

const dialogConfig4SendMailCode = reactive({
  show: false,
  title: "发送邮箱验证码",
  buttons: [
    {
      type: "primary",
      text: "发送验证码",
      click: (e) => {
        sendEmailCode();
      },
    },
  ],
});
const sendEmailCode = () => {
  formData4SendMailCodeRef.value.validate(async (valid) => {
    if (!valid) {
      return;
    }

    const params = Object.assign({}, formData4SendMailCode.value);

    params.type = "1";
    params.email = proxy.VueCookies.get("userInfo").email;
    console.log(params);
    const res = await SendEmailCode(params, () => {
      changeCheckCode(1);
    });
    if (!res) {
      return;
    }
    proxy.Message.success("验证码发送成功，请前往邮箱查看");
    dialogConfig4SendMailCode.show = false;
  });
};
// 重新获取验证码方法
const changeCheckCode = (type) => {
  if (type == 0) {
    checkCodeUrl.value =
      api.checkCode + "?type=" + type + "&time=" + new Date().getTime();
  } else {
    checkCodeUrl4SendMailCode.value =
      api.checkCode + "?type=" + type + "&time=" + new Date().getTime();
  }
};
</script>

<style lang="scss" scoped>
.send-email-panel {
  display: flex;
  width: 100%;
  justify-content: space-between;
  .send-mail-btn {
    margin-left: 5px;
  }
}
.check-code-panel {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  width: 100%;
  .check-code {
    margin-left: 5px;
    cursor: pointer;
  }
}
</style>